import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:http_manager/http_manager.dart';

void main() {
  runApp(const MyApp());
}



extension ResponseAnalyzedExtention on ResponseAnalyzed {
  bool get success    => code == '200';
  bool get failure    => code != '200';

  bool get emptyData  => code == '202';
  bool get noMoreData => code == '203';
}




class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {


  getUserToken(String deviceId) async {
    // 可以不带参数，也可以直接传参数
    final response = httpManager.get("pub/getUserToken/$deviceId");
    /// final response = HttpManager.get("pub/getUserToken/$deviceId", params: {});

    // 解析服务器返回的数据，如果服务器返回的数据格式为: {"code":200, "message":"成功", "data":[{},{}]}
    // 那么 result.code=200， result.message=成功，result.data=[{},{}]
    // 并检查返回结果码，执行需要特殊处理的业务
    // 如果 ResponseAnalyzed.resultCheck 不为空，会先执行该函数，然后再返回 ResponseAnalyzed 对象
    final result = await ResponseAnalyzed.analyzingAndCheckup(response);
    if (result.success) {
      // 通常在这里获取数据，刷新界面
      final userToken = result.data;
      debugPrint(userToken);
    }else {
      if (result.isExposedToUser) {
        SmartDialog.showToast(result.message!);
      }
    }


    // 你也可以使用微任务回调
    httpManager.get("url").then((response) async {
       final result = await ResponseAnalyzed.analyzingAndCheckup(response);
       if (result.success) {
         // 通常在这里获取数据，刷新界面
         final userToken = result.data;
         debugPrint(userToken);
       }else {
         if (result.isExposedToUser) {
           SmartDialog.showToast(result.message!);
         }
       }
    });

    httpManager.getAnalyzing("url").then((result){

    });
  }

  getRequest2(String deviceId) {
    // 你也可以使用微任务回调
    httpManager.get("pub/getUserToken/$deviceId").then((response) async {
      final result = await ResponseAnalyzed.analyzingAndCheckup(response);
      if (result.success) {
        // 通常在这里获取数据，刷新界面
        final userToken = result.data;
        debugPrint(userToken);
      }else {
        if (result.isExposedToUser) {
          SmartDialog.showToast(result.message!);
        }
      }
    });
  }

  getRequest3(String deviceId) {
    // 你也可以使用微任务回调
    httpManager.get("pub/getUserToken/$deviceId").then((response) async {
      final result = await ResponseAnalyzed.analyzingAndCheckup(response);
      if (result.success) {
        // 通常在这里获取数据，刷新界面
        final userToken = result.data;
        debugPrint(userToken);
      }else {
        if (result.isExposedToUser) {
          SmartDialog.showToast(result.message!);
        }
      }
    });
  }


  @override
  void initState() {
    super.initState();

    httpManager.showLog = true;
    httpManager.setBaseParam({"shopId": "1101"});
    httpManager.setHeaders({"UserToken": "2312op323322932094234sdf9435"});
    httpManager.baseUrl = "https://baidu.com";




    // 设置接口返回的业务处理检测过滤，一些特殊的处理。
    // ResponseAnalyzed.resultCheck = (result) {
    //   responseAnalyzedCheckedCallback(result);
    // };
    //

    ResponseAnalyzed.setResultCheck((result) {
      responseAnalyzedCheckedCallback(result);
    });

    setResponseKey("code", "message", "data");


    getUserToken("deviceId");

  }

  static setResponseKey(String? codeKey, String messageKey, String dataKey) {

  }


  // 定义一个具体的回调函数
  responseAnalyzedCheckedCallback(ResponseAnalyzed result) {

    final codeList = [20002, 20003, 27106];
    final code = int.parse(result.code ?? "0");
    if (code == 20401) {
      /// 强制退出登录
      // AppManager.signOut();
    } else if (code > 20000 && code < 30000) {
      result.isExposedToUser = true;
      debugPrint("code: $code, message: ${result.message}");
    } else if (code >= 10000 && code <= 19999) {

      // 直接提示 message
      SmartDialog.showToast(result.message!);
      // 或者使用自定义文字
      // SmartDialog.showToast("code=$code 系统发生错误，请联系管理员");
      // 上传错误日志
      final param = {"code": result.code, "message": result.message, "data": result.data};
      _uploadErrorLogWithResponse(jsonEncode(param));

    } else if (code == 1000) {

      result = ResponseAnalyzed(code: "error", data: "", message: result.message);
      SmartDialog.showToast(result.message!);

    } else if (codeList.contains(code) || (code == 29999 && result.message == "无更多数据")) {
      result.message = "";
    }

  }


  // 上传错误日志
  static Future _uploadErrorLogWithResponse(String response) async {
    // 异常错误，需要上报服务器，方便排查错误
    // debugPrint('uploadErrorLogWithResponse = $response');
  }


  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      builder: FlutterSmartDialog.init(),
      navigatorObservers: [FlutterSmartDialog.observer],
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: const Center(
          child: Text('Running'),
        ),
      ),
    );
  }
}
